package com.zhuiyun.project.api.friend.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zhuiyun.project.api.addfriend.entity.AddFriend;
import com.zhuiyun.project.api.addfriend.mapper.AddFriendMapper;
import com.zhuiyun.project.api.appuser.entity.User;
import com.zhuiyun.project.api.appuser.mapper.AppUserMapper;
import com.zhuiyun.project.api.friend.entity.Friend;
import com.zhuiyun.project.api.friend.mapper.FriendMapper;
import com.zhuiyun.project.api.friend.model.FriendModel;
import com.zhuiyun.project.api.friend.service.FriendService;
import com.zhuiyun.project.api.messagelist.entity.MessageList;
import com.zhuiyun.project.api.messagelist.mapper.MessageListMapper;
import com.zhuiyun.project.api.group.entity.Group;
import com.zhuiyun.project.api.group.service.GroupService;
import com.zhuiyun.project.api.message.config.MessageType;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.util.DateTimeUtils;
import com.zhuiyun.project.util.ObjectUtils;
import com.zhuiyun.project.util.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

import static cn.hutool.poi.excel.sax.ElementName.v;

/**
 * @ClassName FriendServiceImpl
 * @Description TODO 好友 service实现类
 * @Author kdj
 * @Date 2023/6/20 14:20
 **/
@Service
public class FriendServiceImpl implements FriendService {
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private AddFriendMapper addFriendMapper;
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private MessageListMapper messageListMapper;

    @Autowired
    private GroupService groupService;

    @Override
    public Friend addDefault(Friend friend) {
        friend.setDelFlag(0);
        friend.setIsMuted(0);
        friend.setCreateTime(new Date());
        friend.setUpdateTime(new Date());
        return friend;
    }

    /**
     * @param name
     * @param userId
     * @Author kdj
     * @Description 根据name模糊查好友
     * @Date 2023/6/21 9:30
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult getFriendByNameLike(String name, int userId) {
        Example userExample = new Example(User.class);
        // 1. 学号不为空则添加查询条件
        if (ObjectUtils.isNotEmpty(name)) {
            userExample.createCriteria().andLike("userName", "%" + name + "%");
        } else {
            //参数不合法
            return CommonResult.error(EmErrorCode.PARAMETER_VALIDATION_ERROR);
        }
        int i = appUserMapper.selectUserType(userId);
        List<Map> userList = new ArrayList<>();
        if (i == 0) {
            List<Map> users = appUserMapper.getFriendByNameLike(name, userId);
            //判断list是否包含本人user
            userList = users.stream().map(user -> {
                Map map = MapUtil.toCamelCaseMap(user);
                //年龄
                Date userBirthday = (Date) user.get("userBirthday");
                Integer age = null;
                if (userBirthday != null) {
                    try {
                        age = DateTimeUtils.getAge(userBirthday);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                map.put("age", age);
                map.put("chatType", MessageType.PerMsgType);
                return map;
            }).collect(Collectors.toList());
        }
        //判断是不是9位数字
        //如果是的话可能是群聊
        boolean creatable = NumberUtils.isCreatable(name);
        if (creatable & name.length() == 9) {
            //可能是群聊
            Map<Object, Object> map = new HashMap<>();
            Map app = groupService.queryGroupByNum(NumberUtils.createInteger(name), userId, "app");
            Group group = (Group) app.get("group");
            map.put("groupId", group.getId());
            map.put("groupImgId", group.getGroupImgId());
            map.put("groupName", group.getGroupName());
            map.put("groupNum", group.getGroupNum());
            map.put("chatType", MessageType.GroupMsgType);
            map.put("isExist", app.get("isExist"));
            map.put("isAudit", app.get("isAudit"));
            userList.add(map);
        }
        //判断map是否为空
        if (ObjectUtils.isNotEmpty(userList)) {
            return CommonResult.ok(userList);
        } else {
            //查询为空
            return CommonResult.error(EmErrorCode.ID_NOT_OBJECT);
        }

    }

    /**
     * @param userId
     * @Author kdj
     * @Description 根据好友id获取好友信息
     * @Date 2023/6/21 11:27
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult getFriendByFriendUserId(int userId, int friendId) {
        //判断是不是好友关系
        Boolean isFriend = (Boolean) this.isFriend(userId, friendId).getData();
        //创建Example
        Example userExample = new Example(User.class);
        userExample.createCriteria().andEqualTo("id", friendId);
        User user = appUserMapper.selectOneByExample(userExample);
        //存入map
        Map map = new HashMap<>();
        map.put("userId", user.getId());
        map.put("imageId", user.getImageId());
        map.put("userName", user.getUserName());
        map.put("userSex", user.getUserSex());
        //年龄
        Date userBirthday = user.getUserBirthday();
        Integer age = null;
        if (userBirthday != null) {
            try {
                age = DateTimeUtils.getAge(userBirthday);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        map.put("age", age);
        map.put("prohibition", user.getProhibition() == 1 ? true : false);
        map.put("logOff", Integer.parseInt(user.getLogOff()) == 1 ? true : false);
        //是否为好友
        map.put("isFriend", isFriend);
        if (isFriend) {
            //获取好友的留言 获取好友的备注
            Friend friendInfo = this.getFriendInfo(userId, friendId);
            System.out.println(";;;;;;" + friendInfo);
            String remarkName = friendInfo.getRemarkName();
            //获取是否 设置免打扰了
            Integer isMuted = friendInfo.getIsMuted();
            //获取是否免打扰
            map.put("isMuted", isMuted > 0 ? true : false);
            map.put("remarkName", ObjectUtils.isNotEmpty(remarkName) ? remarkName : user.getUserName());
        }
        //判断map是否为空
        if (ObjectUtils.isNotEmpty(map)) {
            return CommonResult.ok(map);
        } else {
            //查询为空
            return CommonResult.error(EmErrorCode.ID_NOT_OBJECT);
        }
    }

    /**
     * @param addFriend
     * @Author kdj
     * @Description 添加Friend数据根据AddFriend数据
     * @Date 2023/6/23 11:59
     * @Return Boolean
     */
    @Override
    @Transactional
    public Boolean addFriendByAddFriend(AddFriend addFriend) {
        //查询之前有没有 添加过好友
        List<Friend> friendList = this.queryIsFriend(addFriend.getUserId(), addFriend.getFriendId());
        if (ObjectUtils.isNotEmpty(friendList)) {
            //修改
            int i;
            for (Friend friend : friendList) {
                friend.setIsMuted(0);
                friend.setDelFlag(0);
                friend.setUpdateTime(new Date());
                //判断之前本人id 是否等于当前 主动请求添加的userId
                if (friend.getUserId() == addFriend.getUserId()) {
                    //如果相同， 修改主动请求人给好友的备注
                    friend.setRemarkName(addFriend.getUserRemarkName());
                } else {
                    //如果不相同， 修改  之前请求的好友给请求人的备注
                    friend.setRemarkName(addFriend.getFriendRemarkName());
                }
                //修改
                i = friendMapper.updateByPrimaryKeySelective(friend);
                if (i < 0) {
                    return false;
                }
            }
            return true;
        } else {
            //创建第一个friend对象
            Friend one = new Friend();
            //userId 是我  friendId 是好友
            one.setUserId(addFriend.getUserId());
            one.setFriendId(addFriend.getFriendId());
            //备注是我给该好友的
            one.setRemarkName(addFriend.getUserRemarkName());
            one = this.addDefault(one);
            //添加
            int i = friendMapper.insertSelective(one);
            Friend two = new Friend();
            two.setUserId(addFriend.getFriendId());
            two.setFriendId(addFriend.getUserId());
            //备注是该好友给我的
            two.setRemarkName(addFriend.getFriendRemarkName());
            two = this.addDefault(two);
            int i1 = friendMapper.insertSelective(two);
            if (i > 0 && i1 > 0) {
                return true;
            }
            return false;
        }
    }

    /**
     * @param userId
     * @param friendId
     * @Author kdj
     * @Description 判断好友关系是否存在
     * @Date 2023/6/29 10:34
     * @Return java.util.List<com.zhuiyun.project.api.friend.entity.Friend>
     */
    @Override
    public List<Friend> queryIsFriend(int userId, int friendId) {
        List<Friend> friendList = friendMapper.queryIsFriend(userId, friendId);
        return friendList;
    }

    /**
     * @param userId
     * @param friendId
     * @Author kdj
     * @Description 获取本人给好友的备注
     * @Date 2023/6/29 15:39
     * @Return String
     */
    @Override
    public String getUserRemarkName(int userId, int friendId) {
        Example example = new Example(Friend.class);
        example.createCriteria().andEqualTo("userId", userId)
                .andEqualTo("friendId", friendId).andEqualTo("delFlag", 0);
        Friend friend = friendMapper.selectOneByExample(example);
        return ObjectUtils.isNotEmpty(friend.getRemarkName()) ? friend.getRemarkName() : "";
    }

    /**
     * @param userId
     * @param friendId
     * @Author kdj
     * @Description 获取好友给本人的备注
     * @Date 2023/6/29 15:43
     * @Return java.lang.String
     */
    @Override
    public String getFriendRemarkName(int userId, int friendId) {
        Example example = new Example(Friend.class);
        example.createCriteria().andEqualTo("friendId", userId)
                .andEqualTo("userId", friendId).andEqualTo("delFlag", 0);
        Friend friend = friendMapper.selectOneByExample(example);
        return friend.getRemarkName();
    }

    /**
     * @param userId
     * @param friendId
     * @Author kdj
     * @Description 判断是否为朋友关系
     * @Date 2023/7/20 21:18
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult isFriend(int userId, int friendId) {
        Example example = new Example(Friend.class);
        example.createCriteria().andEqualTo("userId", userId)
                .andEqualTo("friendId", friendId).andEqualTo("delFlag", 0)
        ;
        int i = friendMapper.selectCountByExample(example);
        return CommonResult.ok(i > 0 ? true : false);
    }

    /**
     * @param userId
     * @param friendId
     * @Author kdj
     * @Description 获取好友信息
     * @Date 2023/7/21 11:50
     * @Return com.zhuiyun.project.api.friend.entity.Friend
     */
    @Override
    public Friend getFriendInfo(int userId, int friendId) {
        Example example = new Example(Friend.class);
        example.createCriteria().andEqualTo("userId", userId)
                .andEqualTo("friendId", friendId).andEqualTo("delFlag", 0)
        ;
        Friend friend = friendMapper.selectOneByExample(example);
        return friend;
    }

    /**
     * @param fromId
     * @param toId
     * @Author kdj
     * @Description 删除成功
     * @Date 2023/7/21 14:15
     * @Return void
     */
    @Override
    public boolean delFriend(Integer fromId, Integer toId) {
        //删除标识
        if (friendMapper.delFriend(fromId, toId) < 1) {
            return false;
        }
        return true;
    }


    /**
     * 温
     * 群聊和单聊消息免打扰功能
     * 该方法用于更新群聊和单聊消息的免打扰功能。
     *
     * @param friend 好友对象，包含免打扰状态、好友ID和用户ID等信息
     * @return 返回受影响的行数
     */
    @Override
    public int updateMeted(Friend friend) {
        int i = 0;
        // 如果好友类型为空，表示为单聊消息
        if (friend.getType() == null) {
            // 更新好友的免打扰状态到Friend表，并返回受影响的行数
            i = friendMapper.updateMeted(friend.getIsMuted(), friend.getFriendId(), friend.getUserId());
            if (i > 0) {
                // 如果受影响的行数大于0，则再次更新好友的免打扰状态到Friend表，并将受影响的行数赋值给i
                i = friendMapper.updateMeted1(friend.getIsMuted(), friend.getFriendId(), friend.getUserId());
            }
        }
        // 如果好友类型为2，表示为群聊消息
        else if (friend.getType() == 2) {
            // 创建一个MessageList对象，并设置其免打扰状态
            MessageList messageList = new MessageList();
            messageList.setIsMuted(friend.getIsMuted());
            // 创建一个Example对象，并根据条件查询对应的MessageList记录
            Example example = new Example(MessageList.class);
            example.createCriteria().andEqualTo("fromId", friend.getFriendId()).andEqualTo("toId", friend.getUserId()).andEqualTo("type", "2");
            // 更新MessageList表中符合条件的记录，并返回受影响的行数
            i = messageListMapper.updateByExampleSelective(messageList, example);
        }
        // 返回受影响的行数
        return i;
    }


    /**
     * 温
     * 修改给好友的备注
     * 该方法用于修改好友的备注信息。
     *
     * @param friend 好友对象，包含好友ID、用户ID和备注信息等信息
     * @return 返回受影响的行数，表示成功修改备注的记录数；返回999999，表示查询出错或未找到符合条件的记录
     */
    @Override
    public int friendUpdate(Friend friend) {
        // 调用friendMapper的friendUpdate方法，更新好友的备注，并返回受影响的行数
        int i = friendMapper.friendUpdate(friend.getRemarkName(), friend.getFriendId(), friend.getUserId());

        String s = friend.getRemarkName(); // 获取好友的备注信息

        // 创建一个MessageList对象，并设置发送人、接收人和好友列表名称
        MessageList messageList = new MessageList();
        messageList.setFromId(friend.getFriendId()); // 将好友ID设置为发送人
        messageList.setToId(friend.getUserId()); // 将用户ID设置为接收人
        messageList.setListName(friend.getRemarkName()); // 将好友的备注信息设置为好友列表名称

        // 根据条件查询对应的MessageList记录，执行单查查询
        MessageList messageList1 = friendMapper.selectOneMessageList(messageList);
        if (messageList1 != null) { // 判断查询结果不为空
            messageList1.getId(); // 获取记录的ID
            messageList1.setListName(s); // 将好友的备注信息赋值给好友列表名称
            // 更新MessageList表中对应的记录，只更新好友列表名称
            messageListMapper.updateByPrimaryKeySelective(messageList1);
            return i; // 返回受影响的行数
        }

        return 999999; // 查询出错或未找到符合条件的记录时，返回999999
    }

    /**
     * 获取好友列表
     *
     * @return java.util.List<com.zhuiyun.project.api.friend.model.FriendModel>
     * @author 温
     * @date 2023/7/27 20:57
     * @parameter [userId]
     */
    @Override
    public List<FriendModel> selectFriend(Friend friend) {
        List<FriendModel> friendModels = friendMapper.selectFriend(friend.getUserId(), friend.getRemarkName());
        return friendModels;
    }


    /**
     * 获取群聊列表信息
     *
     * @return java.util.List<com.zhuiyun.project.api.friend.model.FriendModel>
     * @author 温
     * @date 2023/8/1 23:07
     * @parameter [userId, groupName, groupId]
     */
    @Override
    public List<FriendModel> quancha(Integer userId, String groupName, Integer groupId) {
        List<FriendModel> quancha = friendMapper.quancha(userId, groupName, groupId);
        return quancha;
    }

}